import { Fragment } from "react";
import useAsync from "./useAsync";

export default function UseAsyncToUserList (){
  const { execute: fetchUsers,data:users,loading,error} = useAsync(
    async () => {
      const res = await fetch("https://reqres.in/api/users");
      const json = await res.json();
      return json.data;
    },
  );
  console.log(users,loading)
  return (
    <Fragment>
      <div className="user-list">
        <h1>Use Async Sample</h1>
        <button onClick={fetchUsers} disabled={loading}>
          {
            loading ? "Loading...":"Show Users"
          }
        </button>
        {error && <div style={{color:"red"}}>Failed:{String(error)}</div>}
        <br />
        <ul>
          {
            users && users.length> 0 && users.map((user)=>{
              return (<li key={user.id}>{user.first_name}
                <img src={user.avatar} alt="" />
              </li>)
            })
          }
        </ul>
      </div>
    </Fragment>
  )
}